/**
 * <p>Copyright:Copyright(c) 2019</p>
 * <p>Company:Professional</p>
 * <p>Package:org.cesgroup.course.util</p>
 * <p>File:WordConverter.java</p>
 * <p>类更新历史信息</p>
 *
 * @todo chanlong(陈龙) 创建于 Sep 12, 2019 10:16:50 AM
 */
package org.cesgroup.course.converter;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.itextpdf.html2pdf.HtmlConverter;
import org.cesgroup.course.enumeration.FileType;
import org.cesgroup.course.interceptor.Interceptor;
import org.cesgroup.course.interceptor.Invocation;
import org.cesgroup.course.interceptor.annon.Intercepts;
import org.cesgroup.course.interceptor.annon.Signature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

/**
 * <p>描述: </p>
 * <p>Company: Professional</p>
 *
 * @author chanlong(陈龙)
 * @version 1.0.2019
 * 顺序最靠前，最先执行，最后调用，进行编排操作
 * @date Sep 12, 2019 10:16:50 AM
 */
@Order(0)
@Component
@Intercepts({@Signature(type = Converter.class, method = "process", args = {Object.class, List.class})})
public class HtmlPDFConverter implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        List arg = (List) args[1];
        /**
         *  确定责任链是否可以完成， 即，在顺序没问题的情况下，到达需求的最后一环
         */
        if (arg.contains(FileType.pdf.name()) && arg.size() == 1) {
            return process((byte[]) args[0]);
        }
        boolean remove = arg.remove(FileType.pdf.name());

        Converter converter = (Converter) invocation.getTarget();
        Object process = converter.process(args[0], (List) args[1]);
        /**
         * 重新执行 转换操作，相当于后置处理
         */
        if (remove) {
            File file = new File((String) process);
            byte[] bytes = FileUtil.readBytes(file);
            return process(bytes);
        } else {
            return process;
        }
    }

    private Object process(final byte[] data) throws Throwable {

        String staticpath = locations + "/static/";
        String tmpdir = System.getProperty("java.io.tmpdir");
        String destdir = FileUtil.mkdir(staticpath + "/pdf/").getPath();
        File folder = new File(tmpdir);
        File tempfile = FileUtil.createTempFile(folder);
        File datafile = FileUtil.writeBytes(data, tempfile);
        File pdffile = FileUtil.newFile(destdir + "/" + RandomUtil.randomString(6) + ".pdf");
        HtmlConverter.convertToPdf(datafile, pdffile);

        return pdffile.getPath();
    }

    @Value("${ces.resources.static-location}")
    private String locations;

    String getLocations() {
        return locations;
    }

    void setLocations(String locations) {
        this.locations = locations;
    }

}
